<?php

/**
 * 微商城控制器
 */
class StoreAction extends CommonAction
{
    public $origin;
    public $wechatUserId;        //原FANS_ID
    public $alipayUserId;
    public $wechatId;            //公众 号ID
    public $alipayId;
    //public $accountId;			//账号ID
    public $storeId;
    public $title;
    public $logo;
    public $storeBaseService;
    public $subAccountId;  //后台登录账号ID
    public $cartId;
    public $browser;

    public function _initialize()
    {
        parent::_initialize();



            //通过浏览器调取不用的用户信息和支付信息
            if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') != false) {
                $this->browser = 1;
            }elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Alipay') != false){
                $this->browser = 2;
            }else{
                //$this->error('请在微信或支付宝中打开！');
            }




    }

        public function success()
    {
        $this->assign('type', $this->_get('type'));
        $this->display('success');
        exit;
    }

    public function error($message, $unFooter = 0)
    {
        $this->assign('message', $message);
        $this->assign('unFooter', $unFooter);
        $this->display('error');
        exit;
    }

    /**
     * 保存用户操作信息
     */
    public function clickSave()
    {
        $click_arr = array(
            'store_id' => $this->storeId,
            'user_id' => session('userId') ? session('userId') : 0,
            'group_name' => strtolower(GROUP_NAME),
            'module_name' => strtolower(MODULE_NAME),
            'action_name' => strtolower(ACTION_NAME),
            'create_time' => time(),
            'goods_id' => $this->_get('goods_id')
        );
        if($this->alipayUserId){
            $click_arr['alipay_user_id'] = $this->alipayUserId;
        }
        if($this->wechatUserId){
            $click_arr['wechat_user_id'] = $this->wechatUserId;
        }
        // 		if($click_arr['action_name'] == 'goodsdetail'){
        // 			$click_arr['param_id'] = $this->_get('goods_id');
        // 		}elseif($click_arr['action_name'] == 'goodslist' && $this->_get('cate_id')){
        // 			$click_arr['param_id'] = $this->_get('cate_id');
        // 		}
        if ($this->origin) {
            $click_arr['origin'] = $this->origin;
        }
        M('StoreClick')->add($click_arr);
    }

    /**
     * 首页
     */
    public function index()
    {
        //是否关注
        if ($this->accountId == 12 || $this->accountId == 3) {
            $subscribe = M('WechatUser')->where(array('wechat_user_id' => $this->wechatUserId))->getField('subscribe');
            if ($subscribe == 0) {
                if ($this->accountId == 12) {
                    header('Location: ' . U('/base/html/tlfocus'));
                    exit;
                }elseif ($this->accountId == 3) {
                    header('Location: ' . U('/base/html/glbfocus'));
                    exit;
                }
            }
        }

        //首页数据
        $data['logo'] = $this->logo;
        $data['count'] = $this->storeBaseService->getCount('StoreGoods', array('store_id' => $this->storeId, 'cut_off' => 0, 'disable' => 0));
        $data['cate'] = $this->storeBaseService->getList('StoreGoodsCate', array('store_id' => $this->storeId, 'recommend' => 1, 'cut_off' => 0));
        $data['flash'] = $this->storeBaseService->getList('StoreFlash', array('store_id' => $this->storeId, 'disable' => 0, 'cut_off' => 0, 'type' => 0));
        $field = 'goods_id,goods_name,goods_original_price,goods_price,discount,sale_num,goods_thumb,picked,pay_wechat_id,pay_alipay_id';
        $data['goods'] = $this->storeBaseService->getList('StoreGoods', array('store_id' => $this->storeId,'state'=>2, 'recommend' => 1, 'cut_off' => 0, 'disable' => 0), $field, 'sort asc,goods_id desc', 6);
        foreach ($data['goods'] as $k => $v){
            if ($this->browser == 1){
                if(empty($v['pay_wechat_id'])) {
                    unset($data['goods'][$k]);
                    continue;
                }
                if ($this->wechatId != $v['pay_wechat_id']){
                    $data['goods'][$k]['other'] = 1;
                }
            }elseif ($this->browser == 2){
                if(empty($v['pay_alipay_id'])) {
                    unset($data['goods'][$k]);
                    continue;
                }
                if ($this->alipayId != $v['pay_alipay_id']){
                    $data['goods'][$k]['other'] = 1;
                }
            }
        }

        $url = U('base/store/doGetRecommendGoods', array('store_id' => $this->storeId));
        $this->assign('url', $url);
        $this->view($data);
    }

    /**
     * ajax获取首页商品列表
     */
    public function doGetRecommendGoods(){
        $page = $this->_get('page');
        if (!$page) {
            $page = 2;
        }
        $num = 6;
        $limit = (($page - 1) * 6) . ',' . $num;
        $field = 'goods_id,goods_name,goods_original_price,goods_price,discount,sale_num,goods_thumb,pay_wechat_id,picked,pay_alipay_id';
        $goods = $this->storeBaseService->getList('StoreGoods', array('store_id' => $this->storeId, 'recommend' => 1, 'cut_off' => 0, 'disable' => 0), $field, 'sort asc,goods_id desc', $limit);

        foreach ($goods as $key => $value) {
            $goods[$key]['url'] = U('base/store/goodsdetail', array('store_id' => $this->storeId, 'account_id' => $this->accountId, 'goods_id' => $value['goods_id'], 'origin' => $this->origin));
            if ($this->browser == 1){
                if(empty($v['pay_wechat_id'])) {
                    unset($goods[$key]);
                    continue;
                }
                if ($this->wechatId != $value['pay_wechat_id']){
                    $goods[$key]['other'] = 1;
                }
            }elseif ($this->browser == 2){
                if(empty($v['pay_alipay_id'])) {
                    unset($goods[$key]);
                    continue;
                }
                if ($this->alipayId != $value['pay_alipay_id']){
                    $goods[$key]['other'] = 1;
                }
            }
        }

        $this->ajaxReturn(array('status' => 'S', 'message' => '获取成功', 'data' => $goods ? $goods : array()));
    }

    /**
     * 商品列表
     */
    public function goodsList()
    {
        $get = $this->_get();

        //排序
        $order = '';
        if ($get['order'] == 'recommend') {
            $order .= 'recommend desc,';
        } elseif ($get['order'] == 'sale_num') {
            $order .= 'sale_num desc,';
        } elseif ($get['order'] == 'goods_price') {
            if ($get['order_by'] == 'desc') {
                $order .= 'goods_price desc,';
                $this->assign('order_by', 'asc');
            } else {
                $order .= 'goods_price asc,';
                $this->assign('order_by', 'desc');
            }
        }
        $order .= 'sort asc,goods_id desc';
        $this->assign('order', $get['order']);

        $num = 6;
        $where = array(
            'store_id' => $this->storeId,
            'disable' => 0,
            'cut_off' => 0,
            'state' => 2
        );
        //名字搜索
        if ($get['keyword']) {
            $where['goods_name'] = array('like', '%' . $get['keyword'] . '%');
            $this->assign('keyword', $get['keyword']);
        }
        //分类选择
        if ($get['cate_id']) {
            $where['cate_id'] = $get['cate_id'];
            $this->assign('cate_id', $get['cate_id']);}

        //列表
        $field = 'goods_id,goods_name,goods_original_price,goods_price,discount,sale_num,goods_thumb,pay_wechat_id,pay_alipay_id,picked';
        $data = $this->storeBaseService->getList('StoreGoods', $where, $field, $order, $num);
        foreach($data as $key => $value){
            if ($this->browser == 1){
                if(empty($value['pay_wechat_id'])) {
                    unset($data[$key]);
                    continue;
                }
                if ($this->wechatId != $value['pay_wechat_id']){
                    $data[$key]['other'] = 1;
                }
            }elseif ($this->browser == 2){
                if(empty($value['pay_alipay_id'])) {
                    unset($data[$key]);
                    continue;
                }
                if ($this->alipayId != $value['pay_alipay_id']){
                    $data[$key]['other'] = 1;
                }
            }
        }

        //分类
        $cate = $this->storeBaseService->getList('StoreGoodsCate', array('store_id' => $this->storeId, 'cut_off' => 0));
        $this->assign('cate', $cate);

        $url = U('base/store/doAjaxGetGoodList', array('store_id' => $this->storeId, 'order' => $get['order'], 'order_by' => $get['order_by'], 'keyword' => $get['keyword'], 'cate_id' => $get['cate_id']));
        $this->assign('url', $url);

        $this->view($data);
    }

    /**
     * ajax分页获取商品列表
     */
    public function doAjaxGetGoodList()
    {
        $get = $this->_get();
        $order = '';
        if ($get['order'] == 'recommend') {
            $order .= 'recommend desc,';
        } elseif ($get['order'] == 'sale_num') {
            $order .= 'sale_num desc,';
        } elseif ($get['order'] == 'goods_price') {
            if ($get['order_by'] == 'desc') {
                $order .= 'goods_price desc,';
            } else {
                $order .= 'goods_price asc,';
            }
        }
        $order .= 'sort asc,goods_id desc';

        $page = $get['page'] ? $get['page'] : 2;
        $num = 5;
        $limit = (($page - 1) * 5) . ',' . $num;
        $where = array(
            'store_id' => $this->storeId,
            'disable' => 0,
            'cut_off' => 0
        );
        //名字搜索
        if ($get['keyword']) {
            $where['goods_name'] = array('like', '%' . $get['keyword'] . '%');
        }
        //分类选择
        if ($get['cate_id']) {
            $where['cate_id'] = $get['cate_id'];
        }

        $field = 'goods_id,goods_name,goods_original_price,goods_price,discount,sale_num,goods_thumb,pay_wechat_id,pay_alipay_id,picked';

        $data = $this->storeBaseService->getList('StoreGoods', $where, $field, $order, $limit);

        foreach ($data as $key => $v) {
            $data[$key]['url'] = U('base/store/goodsdetail', array('store_id' => $this->storeId, 'goods_id' => $v['goods_id'], 'origin' => $this->origin));
            if ($this->browser == 1){
                if(empty($v['pay_wechat_id'])) {
                    unset($data[$key]);
                    continue;
                }
                if ($this->wechatId != $v['pay_wechat_id']){
                    $data[$key]['other'] = 1;
                }
            }elseif ($this->browser == 2){
                if(empty($v['pay_alipay_id'])) {
                    unset($data[$key]);
                    continue;
                }
                if ($this->alipayId != $v['pay_alipay_id']){
                    $data[$key]['other'] = 1;
                }
            }
        }
        $this->ajaxReturn(array('status' => 'S', 'message' => '获取成功', 'data' => $data ? $data : array()));
    }

    /**
     * 商品内容页
     */
    public function goodsDetail()
    {
        //是否关注
        if ($this->accountId == 12 || $this->accountId == 3) {
            $subscribe = M('WechatUser')->where(array('wechat_user_id' => $this->wechatUserId))->getField('subscribe');
            if ($subscribe == 0) {
                if ($this->accountId == 12) {
                    header('Location: ' . U('/base/html/tlfocus'));
                    exit;
                }elseif ($this->accountId == 3) {
                    header('Location: ' . U('/base/html/glbfocus'));
                    exit;
                }
            }
        }

        $goodsId = $this->_get('goods_id');

        //杭电新生没有学号
        $userInfo = M('User')->where(array('user_id'=>$this->userId))->field('type,number')->find();
        if ($this->accountId == 25) {//杭电
            $logId = M('AppCustomQuestionnaireLog')->where(array('user_id'=>$this->userId, 'question_id'=>74))->getField('log_id');

            if ($goodsId == '835' && $userInfo['type'] != 1 && !$userInfo['number'] && !$logId) {//新生
                $url = U('/activity/questionnaire/newborn', array('question_id' => 74));
                $this->redirect($url);
            }
        }elseif ($this->accountId == 60){
            $logId = M('AppCustomQuestionnaireLog')->where(array('user_id'=>$this->userId, 'question_id'=>131))->getField('log_id');

            if (!$userInfo['type'] != 1 && !$userInfo['number'] && !$logId) {//新生
                $url = U('/activity/questionnaire/newborn', array('question_id' => 131));
                $this->redirect($url);
            }
        }

        $data = $this->storeBaseService->getInfo('StoreGoods', array('store_id' => $this->storeId, 'goods_id' => $goodsId, 'cut_off' => 0));
        //查找商家账号名字
        $name = M('subAccount')->where(array('sub_account_id'=>$data['sub_account_id']))->field('sub_account_name')->find();
        $data['name'] = $name['sub_account_name'];

        if ($data['cut_off'] == 1) {
            $this->error('该商品已删除');exit;
        } elseif ($data['disable'] == 1) {
            $this->error('该商品已下架');exit;
        }

        //点击操作保存
        $this->clickSave();

        if ($this->browser == 1){
            if ($this->wechatId != $data['pay_wechat_id']){
                $data['other'] = 1;
            }
        }elseif ($this->browser == 2){
            if ($this->alipayId != $data['pay_alipay_id']){
                $data['other'] = 1;
            }
        }

        $data['img'] = $this->storeBaseService->getList('StoreGoodsImage', array('goods_id' => $goodsId),'*','sort ASC');
        $commentCondition = array(
            'goods_id' => $goodsId,
            'goods_comment_time' => array('gt', 0),
        );
        $commentField = 'user_id,goods_star,goods_comment,goods_comment_time,reply_content,comment_picture,cut_picture';
        $data['comment'] = D('OrderGoods')->relation('User')->getList($commentCondition, $commentField, 'order_goods_id desc');
        
        foreach ($data['comment'] as $k => $v) {
            if ($v['real_name']) {
                $data['comment'][$k]['real_name'] = mb_substr($v['real_name'], 0, 1, 'UTF-8') . '****';
            }
        }

        $likeCondition = array(
            'store_id' => $this->storeId,
            'goods_id' => array('neq', $goodsId),
            'cate_id' => $data['cate_id'],
            'cut_off' => 0,
            'disable' => 0
        );
        if($this->browser == 1){
            $likeCondition['pay_wechat_id'] = array('neq',0);
        }
        if($this->browser == 2){
            $likeCondition['pay_alipay_id'] = array('neq',0);
        }
        $field = 'goods_id,goods_name,goods_original_price,goods_price,discount,sale_num,goods_thumb';
        $data['like'] = $this->storeBaseService->getList('StoreGoods', $likeCondition, $field, '', 10);

        $this->storeBaseService->setInc('StoreGoods', array('goods_id' => $goodsId), 'click_num');

        //规格
        $specId = array($data['spec_id_1'], $data['spec_id_2'], $data['spec_id_3']);
        $where = array('spec_id' => array('in', $specId));
        $specArr = $this->storeBaseService->getField('StoreSpec', $where, 'spec_id,spec_name');
        $specArr = array_filter($specArr);

        if ($data['spec_id_1'] || $data['spec_id_2'] || $data['spec_id_3']) {
            $specDate = $this->storeBaseService->getList('StoreGoodsSpec', array('goods_id' => $goodsId));

            foreach ($specDate as $k => $v) {
                if ($v['spec_1'] && $v['spec_2'] && $v['spec_3']) {
                    $spec_1['list'][] = $v['spec_1'];
                    $spec_2['list'][] = $v['spec_2'];
                    $spec_3['list'][] = $v['spec_3'];

                    $goods[$v['spec_1']][$v['spec_2']][$v['spec_3']]['goods_spec_id'] = $v['goods_spec_id'];
                    $goods[$v['spec_1']][$v['spec_2']][$v['spec_3']]['stock'] = $v['stock'];
                    $goods[$v['spec_1']][$v['spec_2']][$v['spec_3']]['price'] = $v['price'];
                }elseif ($v['spec_1'] && $v['spec_2']) {
                    $spec_1['list'][] = $v['spec_1'];
                    $spec_2['list'][] = $v['spec_2'];

                    $goods[$v['spec_1']][$v['spec_2']]['goods_spec_id'] = $v['goods_spec_id'];
                    $goods[$v['spec_1']][$v['spec_2']]['stock'] = $v['stock'];
                    $goods[$v['spec_1']][$v['spec_2']]['price'] = $v['price'];
                }elseif ($v['spec_1']) {
                    $spec_1['list'][] = $v['spec_1'];

                    $goods[$v['spec_1']]['goods_spec_id'] = $v['goods_spec_id'];
                    $goods[$v['spec_1']]['stock'] = $v['stock'];
                    $goods[$v['spec_1']]['price'] = $v['price'];
                }
            }

            if ($data['spec_id_1'] && !empty($spec_1['list'])) {
                $spec_1['spec_name'] = $specArr[$data['spec_id_1']];
                $spec_1['list'] = array_unique($spec_1['list']);
                $array[] = $spec_1;
            }
            if ($data['spec_id_2'] && !empty($spec_2['list'])) {
                $spec_2['spec_name'] = $specArr[$data['spec_id_2']];
                $spec_2['list'] = array_unique($spec_2['list']);
                $array[] = $spec_2;
            }
            if ($data['spec_id_3'] && !empty($spec_3['list'])) {
                $spec_3['spec_name'] = $specArr[$data['spec_id_3']];
                $spec_3['list'] = array_unique($spec_3['list']);
                $array[] = $spec_3;
            }
        }
        $this->assign('goods', json_encode($goods));
        $this->assign('array', $array);

        //地址
        if ($data['picked']) {
            $sinceId = $this->storeBaseService->getField('StoreGoodsSince', array('goods_id' => $goodsId), 'goods_since_id,since_id');
            if($sinceId) {
                $address = $this->storeBaseService->getList('StoreSinceAddress', array('since_id' => array('in', $sinceId)));
            } else {
                $address = array();
            }
        } else {
            $address = array();
        }
        $this->assign('address', $address);

        //查看是否收藏
        $collectionCondition = array(
            'store_id' => $this->storeId,
            'user_id' => $this->userId,
            'goods_id' => $goodsId,
        );
        $collection = $this->storeBaseService->getCount('StoreCollection', $collectionCondition);
        if ($collection) {
            $data['collection'] = 1;
        }

        $shareInfo = array(
            'share_url' => C('site_url') . U('base/store/goodsdetail', array('store_id' => $this->storeId, 'origin' => 'share', 'goods_id' => $goodsId)),
            'share_title' => $data['share_title'] ? $data['share_title'] : $this->title,
            'share_desc' => $data['share_content'] ? $data['share_content'] : $this->title . '欢迎您～',
            'share_image' => $data['goods_thumb'] ? $data['goods_thumb'] : $this->logo
        );
        //商品详情分享
        $this->assign('share_title', $shareInfo['share_title']);
        $this->assign('share_image', $shareInfo['share_image']);
        $this->assign('share_desc', $shareInfo['share_desc']);
        $this->assign('share_url', $shareInfo['share_url']);
        $this->view($data);
    }

    /**
     * 购物车
     */
    public function cart()
    {
        $condition = array('store_id' => $this->storeId);
        if (!$this->userId) {
            if ($this->browser == 2) {
                $condition['alipay_user_id'] = $this->alipayUserId;
            } else {
                $condition['wechat_user_id'] = $this->wechatUserId;
            }
        } else {
            $condition['user_id'] = $this->userId;
        }
        $cart = D('StoreCart')->relation(true)->getList($condition);

        $num = count($cart);
        $otherData = $selfData = array();
        foreach ($cart as $key => $value) {
            $spec = $this->storeBaseService->getInfo('StoreGoodsSpec', array('goods_spec_id'=>$value['goods_spec_id']));
            if ($spec) {
                $specification = $spec['spec_1'];
            }
            if ($spec['spec_2']) {
                $specification .= $spec['spec_2'];
            }
            if ($spec['spec_3']) {
                $specification .= $spec['spec_3'];
            }
            $cart[$key]['specification'] = $specification;
            //如果存在规格价格，则采用规格价格
            $cart[$key]['goods_price'] = $spec['price'] ? $spec['price'] : $cart[$key]['goods_price'];

            $cart[$key]['goods_image'] = $value['goods_thumb'];

            if ($this->browser == 2) {
                if ($value['pay_alipay_id'] == $this->alipayId) {
                    if ($value['picked'] == 1) {
                        $selfData['zt'][] = $cart[$key];
                    } else {
                        $selfData['kd'][] = $cart[$key];
                    }
                } else {
                    if ($value['picked'] == 1) {
                        $otherData[$value['pay_alipay_id']]['zt'][] = $cart[$key];
                    } else {
                        $otherData[$value['pay_alipay_id']]['kd'][] = $cart[$key];
                    }
                }
            } else {
                if ($value['pay_wechat_id'] == $this->wechatId) {
                    if ($value['picked'] == 1) {
                        $selfData['zt'][] = $cart[$key];
                    } else {
                        $selfData['kd'][] = $cart[$key];
                    }
                } else {
                    if ($value['picked'] == 1) {
                        $otherData[$value['pay_wechat_id']]['zt'][] = $cart[$key];
                    } else {
                        $otherData[$value['pay_wechat_id']]['kd'][] = $cart[$key];
                    }
                }
            }
        }

        $this->assign('num', $num);
        $this->assign('otherData', $otherData);
        $this->assign('selfData', $selfData);
        $this->assign('data', $cart);
        $this->display();
    }

    /**
     * 详情页加入购物车
     */
    public function addToCart()
    {
        $post = $this->_post();
        //参数验证
        if (!$post['goods_id'] || !$post['goods_num']) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '参数错误'));
        }
        $data['user_id'] = session('userId');
        if ($this->browser == 2) {
            $data['alipay_user_id'] = $this->alipayUserId;
        } else {
            $data['wechat_user_id'] = $this->wechatUserId;
        }
        $data['goods_id'] = $post['goods_id'];
        $data['goods_spec_id'] = $post['goods_spec_id'] ? $post['goods_spec_id'] : 0;
        //地址
        $data['since_id'] = $post['since_id'];
        $condition = array(
            'user_id' => session('userId'),
            'goods_id' => $data['goods_id'],
            'goods_spec_id' => $data['goods_spec_id'],
            'since_id' => $data['since_id']
        );
        $cartInfo = $this->storeBaseService->getInfo('StoreCart', $condition);

        $goodsInfo = $this->storeBaseService->getInfo('StoreGoods', array('goods_id' => $data['goods_id']), 'stock,on_off,buy_send_time_limit,goods_price');
        //商品库存判断
        if ($data['goods_spec_id'] == 0) {
            $stock = $goodsInfo['stock'];
        } else {
            $spec_info = $this->storeBaseService->getInfo('StoreGoodsSpec', array('goods_spec_id' => $data['goods_spec_id']));
            $stock = $spec_info['stock'];
        }
        if ($stock < $post['goods_num']) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '库存不足'));
        }

        if (($goodsInfo['on_off'] == 1) && ($goodsInfo['buy_send_time_limit'] != 0)) {
            if ($goodsInfo['buy_send_time_limit'] < $post['goods_num']) {
                $this->ajaxReturn(array('status' => 'F', 'message' => '该商品每人限购 ' . $goodsInfo['buy_send_time_limit'] . ' 套'));
            }
        }
        //商品限购次数的限制 by zz at 20151026 10:35 --end

        if ($cartInfo) {
            if ($post['type'] == 'cart') {
                $data['goods_num'] = $post['goods_num'] + $cartInfo['goods_num'];
            } else {
                $data['goods_num'] = $post['goods_num'];
            }
            $data['cart_id'] = $cartInfo['cart_id'];
        } else {
            $data['goods_num'] = $post['goods_num'];
        }

        $data['store_id'] = $this->storeId;
        $data['create_time'] = time();
        $res = M('StoreCart')->update($data);
        if ($res !== false) {
            if ($post['type'] == 'buy') {
                // 避免微支付域名绑定的冲突，采用&链接参数
                $url = '/index.php?g=base&m=store&a=confirmOrder&cart_id=' . $res['cart_id'] . '&store_id=' . $this->storeId;
                $this->ajaxReturn(array('status' => 'S', 'message' => '加入购物车成功', 'confirm_url' => $url));
            } else {
                $this->ajaxReturn(array('status' => 'S', 'message' => '加入购物车成功'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '加入购物车失败'));
        }
    }

    /**
     * 获取购物车信息
     */
    public function getCart()
    {
        $condition = array('store_id' => $this->storeId,);
        if (!$this->userId) {
            if ($this->browser == 2) {
                $condition['alipay_user_id'] = $this->alipayUserId;
            } else {
                $condition['wechat_user_id'] = $this->wechatUserId;
            }
        } else {
            $condition['user_id'] = $this->userId;
        }
        $cart = D('StoreCart')->relation(true)->getList($condition);
        $num = count($cart);
        $otherData = $selfData = array();
        foreach ($cart as $key => $value) {
            $spec = $this->storeBaseService->getByPk('StoreGoodsSpec', $value['goods_spec_id']);
            if ($spec) {
                $specification = $spec['spec_1'];
                if ($spec['spec_2']) {
                    $specification .= $spec['spec_2'];
                }
                if ($spec['spec_3']) {
                    $specification .= $spec['spec_3'];
                }
                $cart[$key]['specification'] = $specification;
                //如果存在规格价格，则采用规格价格
                $cart[$key]['goods_price'] = $spec['price'] ? $spec['price'] : $cart[$key]['goods_price'];
            }
            $cart[$key]['goods_image'] = $value['goods_thumb'];

            if ($this->browser == 2) {
                if ($value['pay_alipay_id'] == $this->alipayId) {
                    if ($value['picked'] == 1) {
                        $selfData['zt'][] = $cart[$key];
                    } else {
                        $selfData['kd'][] = $cart[$key];
                    }
                } else {
                    if ($value['picked'] == 1) {
                        $otherData[$value['pay_alipay_id']]['zt'][] = $cart[$key];
                    } else {
                        $otherData[$value['pay_alipay_id']]['kd'][] = $cart[$key];
                    }
                }
            } else {
                if ($value['pay_wechat_id'] == $this->wechatId) {
                    if ($value['picked'] == 1) {
                        $selfData['zt'][] = $cart[$key];
                    } else {
                        $selfData['kd'][] = $cart[$key];
                    }
                } else {
                    if ($value['picked'] == 1) {
                        $otherData[$value['pay_wechat_id']]['zt'][] = $cart[$key];
                    } else {
                        $otherData[$value['pay_wechat_id']]['kd'][] = $cart[$key];
                    }
                }
            }
        }
        $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'data' => $cart, 'num' => $num, 'otherData' => $otherData, 'selfData' => $selfData));
    }


    /**
     * 更新微信订单openid;如果非自营（既不是自身公众号对应的账户）,用户需要重新进行授权，同力有用到
     * @param $orderId
     */
    public function getPayOpenid($pay_id)
    {
        if ($pay_id != 0 && $pay_id != $this->wechatId) {
            $wechatInfo = D('Wechat/Wechat')->getByPk($pay_id);
            $authCode = $this->_get('code');

            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $backUrl = urlencode($protocol . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI]);
            //青橄榄网络
            if (!$authCode && !$this->_get('openid')) {
                if ($pay_id == 4 || $pay_id == 29 || $pay_id == 30 || $pay_id == 32) {//青橄榄+檬果+北啡+生活帮助手
                    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $wechatInfo['appid'] . '&redirect_uri=' . $backUrl . '&response_type=code&scope=snsapi_base&state=store#wechat_redirect';
                } elseif ($pay_id == 28) {//若拙
                    $url = $protocol . "wap.beescrm.com/Open/AuthUser/auth?url=" . $backUrl;
                } elseif ($pay_id == 27) {//寻食客
                    $url = "http://mall.xunshizheshuo.com/api/oauth_openid.php?url=" . $backUrl;
                }
                header('Location: ' . $url);
            } elseif ($this->_get('openid')) {
                $openid = $this->_get('openid');
            } else {
                vendor('Wechat.WechatApi');
                $cWechat = new WechatApi($wechatInfo['wechat_id']);
                $info = $cWechat->getUserInfoByAuth($authCode, false);
                $openid = $info['data'];
            }
        } else {
            $openid = $this->storeBaseService->getField('WechatUser',array('wechat_user_id' => $this->wechatUserId),'openid');
        }
        return $openid;
    }






    /**
     * 服务窗支付
     */
    public function payAlipayWs($orderId = '')
    {
        if (!$orderId) {
            $orderId = $this->_post('order_id');
        }
        if ($orderId) {
            $order = $this->storeBaseService->getInfo('StoreOrder',array('order_id' => $orderId),'order_sn,picked');
            //支付宝支付成功返回地址
            $returnUrl = C('site_url') . U('base/store/orderlist', array('status' => 1, 'origin' => $this->origin, 'store_id' => $this->storeId, 'picked' => $order['picked']));
            //支付宝异步通知地址
            $notifyUrl = C('site_url') . U('alipay/AlipayNotify/notify');
            $account_id = $this->accountId;
            $prepayData = $this->newPay($account_id, $order['order_sn'], '订单支付', $notifyUrl, $returnUrl);
            if (is_array($prepayData) && $prepayData['status'] == 'F') {
                $this->ajaxReturn(array('status' => 'F', 'message' => $prepayData['message']));
            }
            $result = $prepayData->windowPay();
            if ($result) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '调起支付宝成功', 'url' => $result));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '调起支付宝失败'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '支付宝支付参数错误'));
        }
    }


    /**
     * 支付完成异步通知
     */
    public function notify($order_id, $accountId = '')//
    {
        if($this->_get('order_id')){
            $order_id = $this->_get('order_id');
        }
        RedisService::connectRedis();
        $order = D('Base/StoreOrder')->relation(true)->getByPk($order_id);
        // 扣除商品库存,增加销量
        foreach ($order['StoreOrderGoods'] as $key => $value) {
            $specKey = $value['goods_spec_id'] ? $value['goods_spec_id'] : 0;
            $cacheKey = "string_store_goods_".$value['goods_id']."_".$specKey;
            RedisService::rm($cacheKey);
            RedisService::rm("string_store_order_".$value['user_id']);
            D('Base/StoreGoods')->saleInc($value['goods_id'], $value['goods_spec_id'], $value['goods_num']);

        }
        $storeBaseService = Service('Store/StoreBase');
        //商城筛选出子账号绑定的用户ID
        $order_ids = array();
        foreach($order['StoreOrderGoods'] as $k=>$v){
           $order_ids[] = $v['goods_id'];     
        }
        $orderId = implode(',',$order_ids);
        $subAccountId = M('StoreGoods')->where(array('goods_id'=>array('in',$orderId)))->field('sub_account_id')->select();
        $subAccountIds = array(); 
        foreach($subAccountId as $k=>$v){
            $subAccountIds[] = $v['sub_account_id'];    
        }
        $subAccountIds = implode(',',$subAccountIds);
        $order['sub_account_id'] = $subAccountIds; 
         
        if ($order['pay_type'] && $order['pay_type'] == 2) {
                //如果是浙大商城，支付完成后给管理员推送消息=
            $storeBaseService->sendOrderMessageAlipay($order);
            $storeBaseService->sendRemindMessageAlipay($order);
        } else {
            $storeBaseService->sendOrderMessage($order);
            $storeBaseService->sendRemindMessage($order);
        }
    }



    /**
     * 检查校园卡支付订单状态
     */
    public function checkCampusOrder($dataResonse)
    {

        $praram1 = explode("||", $dataResonse['praram1']);
        $accountId = $praram1[0];
        $payClass = $praram1[1]; //模块支付 1:线上商城支付 2：一码多用支付 3：充值
        $orderId = $praram1[2];
        if (!$accountId) {
            $this->error("account_id不能为空");
        }
        $campuscard = M("Campuscard")->where(array("account_id" => $accountId, "status" => 1))->find();
        //调用接口
        vendor("CampusCard.CampusApi");
        $campusApi = new CampusApi($campuscard);
        //定义偏移向量
        $iv = array('0', '0', '0', '0', '0', '0', '0', '0');
        //请求参数
        $signData = array(
            "tranamt" => $dataResonse['tranamt'], //金额需要乘以100，服务端会除以100
            "orderid" => $dataResonse['orderid'],
            "account" => $dataResonse['account'],
            "sno" => $dataResonse['sno'],
            "toaccount" => $dataResonse['toaccount'],
            "thirdsystem" => $dataResonse['thirdsystem'],
            "thirdorderid" => $dataResonse['thirdorderid'],
            "state" => $dataResonse['state'],
            "orderdesc" => $dataResonse['orderdesc'],
            "praram1" => $dataResonse['praram1']
        );
        //得到签名
        $sign = $campusApi->getSign($signData, $iv);
        if ($sign['status'] == "F") {
            $this->error($sign['message']);
        }
        if ($sign && $sign == urldecode($dataResonse['sign'])) {
            //做逻辑处理
            if($orderId){
                if($payClass == 1) {  //线上商城校园卡支付
                    $orderData = $this->storeBaseService->getInfo('StoreOrder', array('order_id' => $orderId));
                    $orderGoods = $this->storeBaseService->getList('StoreOrderGoods', array('order_id' => $orderId));
                    if ($dataResonse['state'] == 1) {
                        //库存与销量
                        // 扣除商品库存,增加销量
                        foreach ($orderGoods as $key => $value) {
                            D('Base/StoreGoods')->saleInc($value['goods_id'], $value['goods_spec_id'], $value['goods_num']);
                        }
                        $storeBaseService = Service('Store/StoreBase');
                        //发送消息
                        if ($orderData['pay_wechat_id']) {
                            $storeBaseService->sendOrderMessage($orderData);
                            //给绑定订单提醒的管理员发送消息提醒功能
                            $storeBaseService->sendRemindMessage($orderData);
                        } elseif ($orderData['pay_alipay_id']) {
                            $storeBaseService->sendOrderMessageAlipay($orderData);
                            //给绑定订单提醒的管理员发送消息提醒功能
                            $storeBaseService->sendRemindMessageAlipay($orderData);
                        }
                        //支付成功
                        $saveDate = array(
                            'status' => 1,
                            'pay_time' => time(),
                            'is_pay_notify' => 1,
                            'transaction_id' => $dataResonse['orderid']
                        );
                        M('StoreOrder')->where(array('order_id' => $orderId))->save($saveDate);
                        $data = array('binding'=>1);
                        M('CampuscardCard')->where(array('user_id' =>$this->userId))->save($data);
                    }
                }
            }
        } else {
            $this->error("非法数据");
        }
    }


    public function ajaxGetClickList()
    {
        $page = $this->_get('page') ? $this->_get('page') : 2;
        $num = 10;
        $condition = array(
            'store_id' => $this->storeId,
            'user_id' => $this->userId,
            'group_name' => 'base',
            'module_name' => 'store',
            'action_name' => 'goodsdetail',
            'goods_id' => array('gt', 0)
        );
        $limit = (($page - 1) * 10) . ',' . $num;
        $click = $this->storeBaseService->getList('StoreClick',$condition,'DISTINCT(goods_id)','click_id desc',$limit);
        foreach ($click as $k => $v){
            $goodsList[] = $v['goods_id'];
        }

        $goodsOrder = rtrim(implode(',',$goodsList),',');
        $data = $this->storeBaseService->getList('StoreGoods',array('goods_id'=>array('in',$goodsList)),'*','field(goods_id,'.$goodsOrder.')');

        $this->ajaxReturn(array('status' => 'S', 'message' => '获取成功', 'data' => $data ? $data : array()));
    }

    public function reloadQrcode()
    {
        $post = $this->_post();
        $condition = array(
            'order_id' => $post['order_id'],
            'since_id' => $post['since_id'],
            'is_picked' => 0
        );
        $data = $this->storeBaseService->getCount('StoreOrderGoods', $condition);
        if ($data) {
            $this->ajaxReturn(array('status' => 'S', 'message' => '获取成功', 'is_picked' => 0));
        } else {
            $this->ajaxReturn(array('status' => 'S', 'message' => '获取成功', 'is_picked' => 1));
        }
    }

    /**
     * 营业员登录页面
     */
    public function salesLogin()
    {
        $store_id = $this->_get('store_id');
        $order_id = $this->_get('order_id');
        $since_id = $this->_get('since_id');
        if (!cookie('sales_id')) {
            $this->assign('store_id', $store_id);
            $this->assign('order_id', $order_id);
            $this->assign('since_id', $since_id);
            $this->display();
        } else {
            if (cookie('since_id') != $since_id) {
                $this->assign('store_id', $store_id);
                $this->assign('order_id', $order_id);
                $this->assign('since_id', $since_id);
                $this->display();
            } else {
                $url = C('site_url') . '/base/store/sendOrder/store_id/' . $store_id . '/order_id/' . $order_id . '/since_id/' . $since_id . '/can_send/1';
                header("Location:" . $url);
            }
        }
    }

    /**
     * 营业员登录操作
     */
    public function doSalesLogin()
    {
        $post = $this->_post();
        $post['cut_off'] = 0;

        $data = D('StoreSales')->create($post);
        unset($data['since_id']);
        $data['state'] = 2  ;
        $info = $this->storeBaseService->getInfo('StoreSales', $data);

        if (!$info) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '请输入正确的账号和密码'));
        } else {
            setcookie('sales_id', $info['sales_id']);
            $_COOKIE['sales_id'] = $info['sales_id'];
            setcookie('since_id', $info['since_id']);
            $_COOKIE['since_id'] = $info['since_id'];
            if ($info['since_id'] != $post['since_id']) {
                $can_send = 0;
            } else {
                $can_send = 1;
            }
            $url = C('site_url') . '/base/store/sendOrder/store_id/' . $post['store_id'] . '/order_id/' . $post['order_id'] . '/can_send/' . $can_send . '/since_id/' . $post['since_id'];
            $this->ajaxReturn(array('status' => 'S', 'message' => '登录成功', 'url' => $url));
        }
    }

    /**
     * 发货页面
     */
    public function sendOrder()
    {
        $store_id = $this->_get('store_id');
        $order_id = $this->_get('order_id');
        $since_id = $this->_get('since_id');
        $can_send = $this->_get('can_send');
        if (!$order_id || !$since_id) {
            $this->error('参数错误', 1);
        }
        if (!$can_send) {
            $this->error('非本店提货的包裹！', 1);
        }
        $data = D('StoreOrder')->relation(true)->where(array('order_id' => $order_id, 'since_id' => $since_id))->find();
        if ($data['status'] == 3) {
            $this->error('该订单已提货！', 1);
        }
        if($data['order_type'] == 1 && $data['groupon_status'] != 1){
            $this->error('该拼团订单正在拼团中，不能提货！', 1);
        }

        //如果存在规格，则查询
        foreach ($data['StoreOrderGoods'] as $k => $v) {
            if ($v['since_id'] == $since_id) {
                if ($v['goods_spec_id'] > 0) {
                    $goods_spec_id = $v['goods_spec_id'];
                    $spec = D('StoreGoodsSpec')->getByPk($goods_spec_id);
                    if ($v['spec_1']) {
                        $data['StoreOrderGoods'][$k]['spec'] = $v['spec_1'];
                    }
                    if ($v['spec_2']) {
                        $data['StoreOrderGoods'][$k]['spec'] .= $v['spec_2'];
                    }
                    if ($v['spec_3']) {
                        $data['StoreOrderGoods'][$k]['spec'] .= $v['spec_3'];
                    }
                    //如果规格价格存在，则采用规格价格
                    $data['StoreOrderGoods'][$k]['goods_price'] = $spec['price'] ? $spec['price'] : $data['StoreOrderGoods'][$k]['goods_price'];
                } else {
                    $data['StoreOrderGoods'][$k]['spec'] = '';
                }
                if ($v['is_picked']) {
                    $this->error('该包裹已提货！', 1);
                }
            } else {
                unset($data['StoreOrderGoods'][$k]);
            }
        }

        if (!$data) {
            $this->error('订单不存在！', 1);
        }
        $this->assign('store_id', $store_id);
        $this->assign('order_id', $order_id);
        $this->assign('since_id', $since_id);
        $this->view($data);
    }

    /**
     * 发货提交操作
     */
    public function doSendOrder()
    {
        $order_id = $this->_post('order_id');
        $since_id = $this->_post('since_id');
        $sinceNum = $this->storeBaseService->getCount('StoreOrderGoods', array('order_id' => $order_id, 'since_id' => $since_id, 'is_picked' => 0));
        if ($sinceNum > 0) {
            $result = D('StoreOrderGoods')->where(array('order_id' => $order_id, 'since_id' => $since_id))->save(array('is_picked' => 1));
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '该包裹已提货!'));
        }

        $num = $this->storeBaseService->getCount('StoreOrderGoods', array('order_id' => $order_id, 'is_picked' => 0));
        if ($num == 0) {
            $result = D('StoreOrder')->where('order_id = ' . $order_id)->save(array('status' => 3));
        }
        if ($result) {
            $mStoreOrder = D('Base/StoreOrder');
            $order = $mStoreOrder->relation(true)->getByPk($order_id);
            if ($order['pay_type'] == 2) {
                $this->sendOrderSendMessageAlipay($order, $order['account_id']);
            } else {
                $this->sendOrderSendMessage($order, $order['account_id']);
            }
            $this->ajaxReturn(array('status' => 'S', 'message' => '提货成功'));
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
        }
    }

    /**
     * 订单提货成功发送消息（支付宝）
     */
    public function sendOrderSendMessageAlipay($order, $account_id)
    {
        $alipay = M('Alipay')->where(array('account_id' => $account_id,'status'=>1))->field('alipay_id,appid,rsa_private_key')->find();
        if ($order['store_id'] == 21 || $order['store_id'] == 91) { //测试服yungan,正式服goliveaa
            $alipay_user_id = $this->alipayUserId ? $this->alipayUserId : $order['alipay_user_id'];
            $to_user_id = M('AlipayUser')->where(array('alipay_user_id' => $alipay_user_id))->getField('original_alipay_user_id');

            $template_id = '5e9ef747da9c44808e270b3850226531';
            $since_address = '';
            foreach ($order['StoreOrderGoods'] as $k => $v) {
                if (!$since_address) {
                    $since_address = $v['since_address'];
                    break;
                }
            }
            $info = array(
                'head_color' => '#000000',
                'url' => C('site_url') . U('base/store/order', array('store_id' => $order['store_id'], 'order_id' => $order['order_id'])),
                'action_name' => '查看详情',
                'first' => array("color" => "#000000", "value" => '你好，你的订单已自提签收'),
                'keyword1' => array("color" => "#000000", "value" => $order['order_id']),
                'keyword2' => array("color" => "#000000", "value" => $since_address),
                'keyword3' => array("color" => "#000000", "value" => date('Y-m-d H:i:s', time())),
                'remark' => array("color" => "#000000", "value" => "感谢您的使用"),
            );
        }
        if ($alipay) {
            Vendor("Alipay/AlipayApi");
            $alipayApi = new AlipayApi($alipay['alipay_id']);
            $alipayApi->messageTpl( $template_id, $to_user_id, $info);
        }
    }

    /**
     * 订单提货成功发送消息（微信）
     */
    public function sendOrderSendMessage($order, $account_id)
    {
        vendor('Wechat.WechatApi');
        $wechatId = M('Wechat')->where(array('account_id' => $account_id))->getField('wechat_id');
        $weixin = new WechatApi($wechatId);
        $jump_url = '';

        if ($order['store_id'] == 21) {//云感测试
            $appid = 'wxc8142f36a90232b8';
            $appsecret = '8accfa5384286e98f515a4e2b0e8682a';
            $template_id = 'WXFMy--bRgXY_bS97Qg06T9KGaQmBhCeXc_u-JbAmOQ';
            $since_address = '';
            foreach ($order['StoreOrderGoods'] as $k => $v) {
                if (!$since_address) {
                    $since_address = $v['since_address'];
                    break;
                }
            }
            $info = array(
                'first' => array("value" => '你好，你的订单已自提签收'),
                'keyword1' => array("value" => $order['username']),
                'keyword2' => array("value" => $since_address),
                'keyword3' => array("value" => date('Y-m-d H:i:s', time())),
                'remark' => array("value" => "感谢您的使用"),
            );
            $jump_url = C('site_url') . U('base/store/order', array('store_id' => $order['store_id'], 'order_id' => $order['order_id']));
        } elseif ($order['store_id'] == 92) {//正式服充电宝微信商城
            $appid = 'wx1bd34d32c4f77268';
            $appsecret = '16e66297ee247668b9bfec7e5146b883';
            $template_id = 'gnitONzKPb3OZ1khUEtRh-fp1k_WBmeMlDdnwhJXv0Q';
            $since_address = '';
            foreach ($order['StoreOrderGoods'] as $k => $v) {
                if (!$since_address) {
                    $since_address = $v['since_address'];
                    break;
                }
            }
            $info = array(
                'first' => array("value" => '你好，你的订单已自提签收'),
                'keyword1' => array("value" => $order['username']),
                'keyword2' => array("value" => $since_address),
                'keyword3' => array("value" => date('Y-m-d H:i:s', time())),
                'remark' => array("value" => "感谢您的使用"),
            );
            $jump_url = C('site_url') . U('base/store/order', array('store_id' => $order['store_id'], 'order_id' => $order['order_id']));
        } elseif ($order['store_id'] == 85) {//正式服goliveaa测试
            $appid = 'wxc8142f36a90232b8';
            $appsecret = '8accfa5384286e98f515a4e2b0e8682a';
            $template_id = 'vZ1zfixlPdx45rXrnjSKrguj8-Xofe4PrfA0dKq09g8';

            $info = array(
                'first' => array("value" => '订单发货成功'),
                'keyword1' => array("value" => $order['order_sn']),
                'keyword2' => array("value" => ''),
                'keyword3' => array("value" => date('Y-m-d H:i:s', time())),
                'remark' => array("value" => ""),
            );
        }
        elseif ($order['store_id'] == 95) {//正式服中医药
            $appid = 'wxd6c4ce45bd5b99a9';
            $appsecret = '3753e605fa7a85d2f46cf90139bb19f7';
            $template_id = 'Zk3PqcmeuuaxWDcfU7vV6WM6ehVr089H7qQUsBPXAnQ';
            $goods_name = '';
            foreach ($order['StoreOrderGoods'] as $key => $value) {
                if (strlen($goods_name) > 40) {
                    $goods_name .= '等商品';
                } else {
                    $goods_name .= $value['goods_name'] . ' ';
                }
            }
            $info = array(
                'first' => array("value" => '您的包裹已领取！'),
                'keyword1' => array("value" => $order['order_sn']),
                'keyword2' => array("value" => $order['order_amount'] . '元'),
                'keyword3' => array("value" => $goods_name),
                'remark' => array("value" => "感谢您的光临！"),
            );
            $jump_url = C('site_url') . U('base/store/order', array('store_id' => $order['store_id'], 'order_id' => $order['order_id']));
        }
        if ($appid) {
            $wechat_user_id = $order['fans_id'];
            $openId = $this->storeBaseService->getField('WechatUser', array('wechat_user_id' => $wechat_user_id), 'openid');

            $weixin->messageTpl($appid, $appsecret, $openId, $template_id, $info, $jump_url);
        }
    }

    /**
     * 绑定消息管理员
     */
    public function remind()
    {
        //是否已申请
        $condition = array('store_id' => $this->storeId,'is_del' => 0,'sub_account_id' => $this->subAccountId);
        if($this->alipayUserId) {
            $condition['alipay_user_id'] = $this->alipayUserId;
        }
        if($this->wechatUserId){
            $condition['wechat_user_id'] = $this->wechatUserId;
        }
        $user = $this->storeBaseService->getInfo('StoreRemindUser', $condition, 'status,is_del', 'remind_id DESC');
        //是否有数据
        if (!$user) {
            $status = 3;
        } else {
            //是否被删除(用不到了)
            if ($user['is_del'] == 1) {
                $status = 2;
            } else {
                $status = $user['status'];
            }
        }
        $this->assign('status', $status);

        if ($this->browser == 2) {
            $is_sub = 2;
        } else {
            //是否关注了公众号 (支付宝生活号获得是否关注需要获取整个关注者列表，然后去匹配包含)
            //$is_sub = $this->storeBaseService->getField('WechatUser', array('wechat_user_id' => $this->wechatUserId), 'subscribe');
            $is_sub = 1;
        }
        $this->assign('is_sub', $is_sub);
        $this->display();
    }

    /**
     * 消息管理员注册页面
     */
    public function remindBind()
    {
        $this->display();
    }

    /**
     * 消息管理员绑定操作
     */
    public function doRemindBind()
    {
        $post = $this->_post();
        $condition = array(
            'is_del' => 0,
            'store_id' => $post['store_id'],
            'sub_account_id' => $post['sub_account_id']
        );
        if($this->alipayUserId) {
            $condition['alipay_user_id'] = $this->alipayUserId;
        }
        if($this->wechatUserId){
            $condition['wechat_user_id'] = $this->wechatUserId;
        }
        $count = $this->storeBaseService->getCount('StoreRemindUser', $condition);
        if ($count < 1) {
            $time = time();
            $data = array(
                'store_id' => $post['store_id'],
                'user_name' => $post['user_name'],
                'mobile' => $post['mobile'],
                'status' => 0,
                'is_del' => 0,
                'create_time' => $time,
                'upadate_time' => $time,
                'sub_account_id' => $post['sub_account_id']
            );
            if($this->alipayUserId) {
                $data['alipay_user_id'] = $this->alipayUserId;
            }
            if($this->wechatUserId){
                $data['wechat_user_id'] = $this->wechatUserId;
            }
            $res = M('StoreRemindUser')->add($data);
            if ($res) {
                $url = U('/base/store/remind', array('store_id' => $post['store_id']));
                $this->ajaxReturn(array('status' => 'S', 'message' => '绑定成功', 'url' => $url));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '绑定失败'));
            }
        } else {
            $this->ajaxReturn(array('status' => 'F', 'message' => '您已申请绑定，请等待管理员审核'));
        }
    }

    /**
     * 地址列表页
     */
    public function address()
    {
        $picked = $this->_get('picked') ? $this->_get('picked') : 0;
        $this->assign('picked', $picked);
        $condition = array('account_id' => $this->accountId, 'cut_off' => 0);
        //不需要注册用户只能通过微信id
        if ($this->userId == 0) {
            if ($this->browser == 2) {
                $condition['alipay_user_id'] = $this->alipayUserId;
            } else {
                $condition['wechat_user_id'] = $this->wechatUserId;
            }
        } else {
            if ($this->browser == 2) {
                $map['alipay_user_id'] = $this->alipayUserId;
            } else {
                $map['wechat_user_id'] = $this->wechatUserId;
            }
            $map['user_id'] = $this->userId;
            $map['_logic'] = 'or';
            $condition['_complex'] = $map;
            $condition['_logic'] = 'and';
        }
        $data = $this->storeBaseService->getList('UserAddress',$condition);
        $this->view($data);
    }

    /**
     * 新增/修改地址
     */
    public function addAddress()
    {
        //查询用户的角色是学生还是老师
        $roleType = $this->storeBaseService->getField('User',array('user_id' => $this->userId),'type');
        if ($roleType == '') {
            $roleType = 2;
        }

        if (IS_POST) {
            $data = M('UserAddress')->create();
            $data['account_id'] = $this->accountId;

            $data['user_id'] = $this->userId;
            if ($this->browser == 2) {
                $data['alipay_user_id'] = $this->alipayUserId;
            } else {
                $data['wechat_user_id'] = $this->wechatUserId;
            }
            $data['user_type'] = $roleType;     //用户角色类型：0学生 ，1教师
            $data['create_time'] = time();
            $data['type'] = $this->_post('picked') ? $this->_post('picked') : 0;
            $res = M('UserAddress')->update($data);
            if ($res === false) {
                $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败'));
            } else {
                $this->ajaxReturn(array('status' => 'S', 'message' => '操作成功', 'picked' => $this->_post('picked'), 'store_id' => $this->storeId));
            }
        } else {
            $picked = $this->_get('picked') ? $this->_get('picked') : 0;
            $addressId = $this->_get('address_id');
            $city = array();
            $district = array();
            if ($addressId) {
                $data = $this->storeBaseService->getInfo('UserAddress',array('address_id'=>$addressId));
                $this->assign('address_id', $addressId);
                if($data['province_id']){
                    $city=M('StoreArea')->where(array('area_level'=>2,'status'=>1,'parent_id'=>$data['province_id']))->select();
                }
                if($data['city_id']){
                    $district=M('StoreArea')->where(array('area_level'=>3,'status'=>1,'parent_id'=>$data['city_id']))->select();
                }
            }
            $provice=M('StoreArea')->where(array('area_level'=>1,'status'=>1))->select();

            $this->assign('province', $provice);
            $this->assign('city', $city);
            $this->assign('district', $district);
            $this->assign('picked', $picked);
            $this->assign('userType', $roleType);
            $this->assign('accountId', $this->accountId);
            $this->view($data);
        }
    }

    /**
     * ajax获取当前省份的城市数据
     */
    public function getCity()
    {
        $provinceId = $this->_post('province_id');
        if(!$provinceId){
            $this->ajaxReturn(array('status'=>'F','message'=>'请先选择省份'));
        }
        $city = $this->storeBaseService->getList('StoreArea',array('area_level'=>2,'status'=>1,'parent_id'=>$provinceId));
        $this->ajaxReturn(array('status'=>'S','data'=>$city));
    }

    /**
     * ajax获取当前城市的县区数据
     */
    public function getDistrict()
    {
        $cityId = $this->_post('city_id');
        if(!$cityId){
            $this->ajaxReturn(array('status'=>'F','message'=>'请先选择城市'));
        }
        $district = $this->storeBaseService->getList('StoreArea',array('area_level'=>3,'status'=>1,'parent_id'=>$cityId));
        $this->ajaxReturn(array('status'=>'S','data'=>$district));
    }

    /**
     * 设置默认地址
     */
    public function addressDefault()
    {
        $addressId = $this->_post('address_id');
        // 将所有地址都取消默认
        $condition = array('account_id' => $this->accountId, 'cut_off' => 0);
        if ($this->userId == 0) {
            if ($this->browser == 2) {
                $condition['alipay_user_id'] = $this->alipayUserId;
            } else {
                $condition['wechat_user_id'] = $this->wechatUserId;
            }
        } else {
            if ($this->browser == 2) {
                $map['alipay_user_id'] = $this->alipayUserId;
            } else {
                $map['wechat_user_id'] = $this->wechatUserId;
            }
            $map['user_id'] = $this->userId;
            $map['_logic'] = 'or';
            $condition['_complex'] = $map;
            $condition['_logic'] = 'and';
        }
        M('UserAddress')->where($condition)->save(array('default' => 0));
        // 设置默认地址
        $res = M('UserAddress')->where(array('address_id' => $addressId))->save(array('default' => 1));
        if ($res === false) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '操作失败，请稍后再试'));
        } else {
            $url = '/index.php?g=base&m=store&a=confirmOrder';

        //            $str = '';
        //            foreach ($this->otherData as $key => $v) {
        //                $str = $str . $key . '=' . $v . '&';
        //            }
            $url = C('site_url') . $url . '&' . 'store_id=' . $this->storeId . '&cart_id=' . $this->cartId;
            if ($url) {
                $this->ajaxReturn(array('status' => 'S', 'message' => '设置默认地址成功', 'url' => $url));
            } else {
                $this->ajaxReturn(array('status' => 'F', 'message' => '设置默认地址失败'));
            }

        }
    }

    /**
     * 删除地址
     */
    public function delAddress()
    {
        $res = M('UserAddress')->update();
        if ($res === false) {
            $this->ajaxReturn(array('status' => 'F', 'message' => '删除失败'));
        } else {
            $this->ajaxReturn(array('status' => 'S', 'message' => '删除成功'));
        }
    }

    /**
     * 获取物流信息
     * 用于日查询小于3000的
     */
    public function express()
    {
        $orderId = $this->_get("order_id");
        if(!$orderId){
            $this->error("订单不存在");
        }
        $data = D('StoreOrder')->relation('StoreOrderGoods')->getByPk($orderId);
        if(!$data){
            $this->error("订单不存在");
        }
        $in_cate = '';
        $not_goods = '';
        foreach ($data['StoreOrderGoods'] as $k=>$v){
            $in_cate .= $v['cate_id'].',';
            $not_goods .= $v['goods_id'].',';
        }
        $in_cate = rtrim($in_cate,',');
        $not_goods = rtrim($not_goods,',');
        if($in_cate && $not_goods){
            $likeCondition = array(
                'store_id' => $this->storeId,
                'goods_id' => array('not in ', $not_goods),
                'cate_id' => array('in',$in_cate),
                'cut_off' => 0,
                'disable' => 0
            );
            if($this->browser == 1){
                $likeCondition['pay_wechat_id'] = array('neq',0);
            }
            if($this->browser == 2){
                $likeCondition['pay_alipay_id'] = array('neq',0);
            }
            $field = 'goods_id,goods_name,goods_original_price,goods_price,discount,sale_num,goods_thumb';
            $limit = '0,10';
            $data['like'] = $this->storeBaseService->getList('StoreGoods', $likeCondition, $field,'',$limit);
        }
        //引入Api,实例化类
        vendor("Express.ExpressApi");
        $express=new ExpressApi();
        //调用方法getOrderTracesByJson('订单号，可为空','快递公司代码','快递单号')；返回json字符串
        $request=$express->getOrderTracesByJson('',$data['ship_type_code'],$data['ship_code']);
        //解码json字符串
        $obj_req=json_decode($request);
        //解码出来里面既有对象也有数组，需要看清楚类型再使用
        $data['express'] = $obj_req->Traces;
        rsort($data['express']);
        $this->view($data);
    }

    /**
     * 校园卡绑定页面
     */
    public function bound(){

        $this->display();
    }
    /**
     * 校园卡解绑
     */
    public function unbound(){
        $user_id = $this->_get('user_id');
        $password = $this->_post('last_six_bit');
        $pass = M('CampuscardCard')->where(array('user_id'=>$user_id))->find();

        if($password == $pass['password']){
            $data = array('status'=>0);
            $result = M('CampuscardCard')->where(array('user_id'=>$user_id))->save($data);
            if($result){
                $this->ajaxReturn(array('status'=>'S'));
            }
        }
         $this->ajaxReturn(array('status'=>'F','message'=>'密码错误解绑失败'));
        
    } 

    /**
     * 微信个人中心跳转方法
     */
    public function zhuan(){
       //校园卡
        $info = D("CampuscardCard")->where(array('user_id'=>$this->userId))->find();
        $account_id = $this->_get('account_id');
        //已绑卡
        if(!$info || $info['status'] ==0){
            //未绑卡
            $this->redirect("bound",array('store_id'=>$this->storeId,'account_id'=>$account_id,'user_id'=>$this->userId,'on'=>1,'go'=>2));  
        }
            $this->redirect("center",array('store_id'=>$this->storeId,'user_id'=>$this->userId,'account_id'=>$account_id));
        
    }
    /**
     * 添加校园卡
     */
    public function add(){
        $info['user_id'] = $this->_post('user_id');
        $info['campuscard_id'] = $this->_post('campuscard_id');
        $info['number'] = $this->_post('name');
        $info['number2'] = $this->_post('name1');
        $info['password'] = $this->_post('pass');
        $info['create_time'] = time();
        
        //结果1 防止直接进入页面添加
        $test1 = M("CampuscardCard")->where(array('user_id'=>array('eq', $info['user_id']),'status'=>array('eq','1')))->find();
        if($test1){
            $this->ajaxReturn(array('status' => 'F', 'message' => '账户已经添加校园卡')); 
        }

         //结果2 新添加校园卡
        $result = M("CampuscardCard")->where(array('user_id'=>array('eq', $info['user_id'])))->find();
        if(!$result){
            $result = M("CampuscardCard")->update($info);
            if($result){
                $this->ajaxReturn(array('status' => 'S', 'message' => '添加成功','store_id' => $this->storeId,'user_id'=>$info['user_id']));
            }
                $this->ajaxReturn(array('status' => 'F', 'message' => '添加失败'));
        }


        //结果3 解绑之后，从新添加
        $test = M("CampuscardCard")->where(array('user_id'=>array('eq', $info['user_id']),'status'=>array('eq','0')))->find();
        if($test){
            $info['status'] = 1; 
             $result = M("CampuscardCard")->where(array('user_id'=>array('eq',$info['user_id'])))->save($info);
            if($result){
                $this->ajaxReturn(array('status' => 'S', 'message' => '添加成功','store_id' => $this->storeId,'user_id'=>$info['user_id']));
            }       
        }else{
             $this->ajaxReturn(array('status' => 'F', 'message' => '添加失败'));    
        }
           
    }

    /**
     * 校园卡中心
     */
    public function center(){
        $info['user_id'] = $this->_get('user_id');
        $account_id = $this->_REQUEST('account_id');
        $go = $this->_REQUEST('go');
        $data = D("CampuscardCard")->where(array('user_id'=>array('eq', $info['user_id'])))->find();
         $store_id = $this->_get('store_id');
         $this->assign('account_id',$account_id);
        $this->assign('store_id',$store_id);
        $this->assign('go',$go);
        $this->assign('data',$data);
        $this->display();
    }
}